// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require(CONFIG.BasePath + "js/enterprise/base");
	var router = require("../hash/pageRouter");
	var footer = require("../footer/footer_gray");
	var top = require("../top/top_white");
	var dialog = require("dialog");
	var validate = require("validate");
	var flag = false;
	var i = 2;
	var html;
	var commodityCategoryId; //货物类别ID
	var tools = require("tools");
	var commodityNames = []; //  货物名称
	var specifications = []; //  规格型号
	var commodityNumbers = []; //  货物编号
	var originPlaces = []; //  产地
	var quantitys = []; //  数量
	var units = []; //  单位
	var weights = []; //  重量
	var volumes = []; //  体积
	var publicity = []; //  是否公示
	var manufacturers = []; //  生产厂家
	var bulkstockIds = [];
	var bulkstockIds1 = [];
	var bulkstockPrice = [];
	var productType;
	var productName;
	var interest;
	var financeId;
	var userID;
	var PONO;
	var bulkstockValuation;
	var databind = require("databind");
	var html_valuation = require("./apply_valuation.html");
	var nd = $("#goods1").clone();
	var addFreightInfoDom = $(".freightListInfos:first").clone();
	var html_createSuppliers = require("./html_createSuppliers.html");
	var pageIndex = 1,
		pageSize = 5,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化

	var bulkstockObj = {
		bulkstockId: [],
		bulkstockName: [],
		specificationName: [],
		bulkstockNumber: [],
		measurement: [],
		conversionFactor: []
	};

	var commodities = {
		bulkstockCategoryId: [],
		publicity: [],
		volumes: [],
		weights: [],
		units: [],
		quantitys: [],
		originPlaces: [],
		commodityNumbers: [],
		specifications: [],
		manufacturers: [],
		commodityNames: [],
		bulkstockIds: [],
		bulkstockIds1: [],
		bulkstockValuations: [],
		bulkstockPrices: [],
		coldStorage: [],
		dangerous: [],
		declaration: [],
		instructionManual: [],
		dangerousRemark: [],
		unNum: [],
		imdg: [],
		coolLetter: [],
		coolRemark: [],
		vent: [],
		tempMin: [],
		tempMax: [],
		tempUnit: [],
		setTemperature: [],
		tempUpDown: [],
		plugType: [],
		ptiOk: [],
		plug: [],
		precool: [],
		cargoMark: []
	};
	var init = function() {
		financeId = base.getUrlParam("financeId");
		productType = base.getUrlParam("productType");
		userID = base.getUrlParam("userID");
		PONO = base.getUrlParam("PONO");
		
		if (userID != null) {
			loginByUserId(userID);
		}
		
		$("select[name=pledgeRate]").html();
		for(var i = 85; i >= 20; i-=1) {
			var str = '<option value="'+i+'">'+i+'%</option>';
			$("select[name=pledgeRate]").append(str);
		}
		
		//  	financeId = 547;
		$("#apply_main input[name=productType]").val(productType);
		top.init("借款申请");
		footer.init();
		$("#head").removeClass("none");
		$(".login").addClass("none");
		$("#main").removeClass("none");
		$("#footer").removeClass("none");
		getCommodityCategory();
		inquireCurrentEnterpriseDetail();
		router.init();
//		tools.clearNoNumAll($("#main"));
//		$($("#main input[num=1]")).divide();
		initEvent();
	};

	var initEvent = function() {
//		新增运费单信息
		$(".addFreightListInfo").unbind("click").click(function(){
			var str = '<tr><td><input name="shipNames" type="text"/></td><td><input codeName="运单号" name="waybillNumbers" class="toUp" type="text"/></td><td><input class="toUp" codeName="箱号" name="caseNumbers" type="text"/></td><td><input name="caseSizes" type="text"/><td><input name="doorsAdresses" type="text"/><td><input name="settlementPrices" type="text"/><td><input name="settlementObjects" type="text"/><td><input name="remarks" type="text"/><td><input name="confirmDates" readonly="readonly" onfocus="WdatePicker({})" type="text"/></td><td><input name="settlementDates" readonly="readonly" onfocus="WdatePicker({})" type="text"/></td><td><a class="deleteFreightListInfo" href="javascript:void(0);">删除</a></td></tr>';
			$(".freightListInfo tbody").append(str);
			
			tools.clearNoNum($("input[name=settlementPrices]:last"));
			
			$("input[name=quantitys]").val($(".freightListInfo table tr").length - 1);
		});
		
		//删除运费单信息
		$("#apply_main").on("click", ".deleteFreightListInfo", function(){
			$(this).parents("tr").remove();
			
			$("input[name=quantitys]").val($(".freightListInfo table tr").length - 1);
					
			var v = 0;
			$.each($("#apply_main input[name=settlementPrices]"), function() {
				if ($(this).val() != null) {
					v = v + $(this).val()*1;
				}
			});
			$("#bulkstockValuation").val(v);
			$("#valuation").val(v);
			$("#apply_main input[name=bulkstockPrice]").val(v);
		});
		
		$("#apply_main").on("keyup", ".bulkstockPrice", function(){
			var valuation = $("input[name=bulkstockPrice]").val()*$("input[name=quantitys]").val();
			if (!isNaN(valuation)) {
				$("#apply_main input[name=valuation]").val(valuation);
				
				var valuation1 = $("select[name=pledgeRate]").val()*$("input[name=valuation]").val()/100;
				if (!isNaN(valuation1)) {
					$("#apply_main input[name=applicationAmount]").val(valuation1);
				}
			}
		});
		
		$("#apply_main").on("keyup", ".quantitys", function(){
			var valuation = $("input[name=quantitys]").val()*$("input[name=bulkstockPrice]").val();
			if (!isNaN(valuation)) {
				$("#apply_main input[name=valuation]").val(valuation);
				
				var valuation1 = $("select[name=pledgeRate]").val()*$("input[name=valuation]").val()/100;
				if (!isNaN(valuation1)) {
					$("#apply_main input[name=applicationAmount]").val(valuation1);
				}
			}
		});
		
		$("#apply_main").on("change", "select[name=pledgeRate]", function(){
			var valuation1 = $(this).val()*$("input[name=valuation]").val()/100;
			if (!isNaN(valuation1)) {
				$("#apply_main input[name=applicationAmount]").val(valuation1);
			}
		});
		
		if (financeId != null) {
			inquireFinanceApplicationDetail();
		}

		$("#apply_main").on("change", "input[name=applicationAmount]", function() {
		});

		changeBulkstockValuationEven();

		

		$("#apply_main_next").click(function() {
			
			
			var cm = $(".data[name=creditLineRemains]").html();
			var d = $("#applicationAmount").val();
			
			if ((d/10000)*1 > cm*1) {
				base.alert(2, "授信额度不足！");
				return;
			}
			
			//对属性赋值
			financeId = $("#financeId").val();
			
			if (financeId.length != 0) {
				$(".financeApplicationContent").attr("action", "updateFinanceApplication");
			} else {
				$(".financeApplicationContent").attr("action", "createFinanceApplication");
			}

			var promptString = validate.isPhone($("#receiveContactPhone"));
			if (promptString.length > 0) {
				base.alert(2, "收货联系人电话" + promptString);
				return;
			}
			promptString = validate.isPhone($("#deliverContactPhone"));
			if (promptString.length > 0) {
				base.alert(2, "交货联系人电话" + promptString);
				return;
			}
			
			databind.submitDom($(".financeApplicationContent"), function(data) {
				commodityCategoryId = $("#commodityCategory").val();
				if (financeId.length != 0) {
					router.route("apply/apply_upload_material.html?financeId=" + financeId + "&bulkstockCategoryId=" + commodityCategoryId + "&userID=" + userID + "&productType=" + productType, true);
				} else {
					router.route("apply/apply_upload_material.html?financeId=" + data.datas[0].financeId + "&bulkstockCategoryId=" + commodityCategoryId + "&userID=" + userID + "&productType=" + productType, true);
				}

			});

		});

		//改变货物类别
		$("#main").on("change", "#commodityCategory", function() {
			if ($(this).val() != "") {
				inquireBulkstockPageList($(this).val(), $(".commodityNames"));
				inquireBulkstockCategoryDetail($(this).val());
				$("#commodityCategoryHidden").val($("#commodityCategory  option:selected").text());
			} else {
				$(".bulkstockMaterial").addClass("none");
			}
		});
		//改变货物
		$("#main").on("change", ".commodityNames", function() {
			var commodityName = $(this).parent().find("option:selected").text();
			$(this).parent().find(".bulkstockNames").val(commodityName);
			$(this).parent().find(".measurement").val($(this).parent().find("option:selected").attr("measurement"));
			$(this).parent().find(".conversionFactor").val($(this).parent().find("option:selected").attr("conversionFactor"));
			existBulkstockPledgeRate($(this).val(), null, null);
		});

		$("#main").on("change", "#applicationAmount", function() {
			var v = $("#valuation").val();
			var a = $("#applicationAmount").val();
			if ($.trim(v) == "") {
				return;
			}
			
			$(".adv span").html((a * 100/v).toFixed(2));
			
			$.each($("select[name=bulkstockInfoIds]"), function(){
				if ($(this).val() == null || $(this).val() == "") {
					layer.msg("请先选择融资货物");
					return;
				}
				existBulkstockPledgeRate($(this).val(), $(".adv span").html(), null);
			});
		});

		if (productType == 1 || productType == 5 || productType == 6) {
			$("select[name=packingMethod]").parent().removeClass("none");
			$(".goodsfrom").remove();
			$(".deliverEnterprise").next().remove();
			$(".deliverEnterprise").remove();
			$(".send_contact").remove();
			$(".receiver").html("供应")
			$("#addCaseInfo").parent().remove();
			$(".receive_date").removeClass("none");
			$(".receiveEnterprise").append("<a href='javascript:void(0);' class='addSupplier'>添加</a>");
			
			tools.inquireCommonSelectorListByName("运费承担", $("select[name=transportExpenseBear]"));
			tools.inquireCommonSelectorListByName("运费承担", $("select[name=transportMethod]"));
			tools.inquireCommonSelectorListByName("包装样式", $("select[name=packingMethod]"));
		}
	};
	
	var inquireCurrentEnterpriseDetail = function() {
		base.fnAjax({
			action: "inquireCurrentEnterpriseDetail.json",
			async: false,
			oData: {
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm($(".creditLineDom"), data.datas[0].enterpriseGradeDetail);
					$(".data[name=creditLine]").html(($(".data[name=creditLine]").html()/10000).toFixed(2));
					$(".data[name=creditAlready]").html(($(".data[name=creditAlready]").html()/10000).toFixed(2));
					$(".data[name=creditLineRemains]").html(($(".data[name=creditLineRemains]").html()/10000).toFixed(2));
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};

	//获取融资信息详情
	var inquireFinanceApplicationDetail = function() {
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			async: false,
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					databind.fillForm($("#main"), data.datas[0]);
					//					inquireBulkstockPageList(data.datas[0].bulkstockCategoryId);
					if (data.datas[0].containerBills.length > 0) {
						var table = ['<table cellpadding="0" cellspacing="0">',
							'							<tr><th>尺寸</th><th>箱型</th><th>空重</th><th>箱量</th><th>SOC</th><th>操作</th></tr>',
							'						</table>'
						].join("");

						$("#addCaseInfo").before(table);
						var d = $("#addCaseInfo").parent().find("table");

						var tr = '<tr><td><select name="dimension"><option value="10">10</option><option value="20">20</option><option value="40">40</option><option value="48">48</option></select></td><td><select name="model"><option value="GP">GP</option><option value="HQ">HQ</option><option value="RH">RH</option></select></td><td><input readonly="readonly" value="F" name="emptyWeight" type="text"></td><td><input isNull="1" codeName="订舱箱量" name="quantity" type="text"></td><td><input type="hidden" name="soc" value="0" class="valueInput" /><input class="soc" type="checkbox"></td><td><a class="delete">删除</a></td></tr>';

						$.each(data.datas[0].containerBills, function() {
							var tr = '<tr><td><select value="' + this.dimension + '" name="dimension"><option value="10">10</option><option value="20">20</option><option value="40">40</option><option value="48">48</option></select></td><td><select value="' + this.model + '" name="model"><option value="GP">GP</option><option value="HQ">HQ</option><option value="RH">RH</option></select></td><td><input readonly="readonly" value="F" name="emptyWeight" type="text"></td><td><input isNull="1" codeName="订舱箱量" value="' + this.quantity + '" name="quantity" type="text"></td><td><input name="soc" type="hidden" value="' + this.soc + '" class="valueInput" /><input class="soc" value="' + this.soc + '" type="checkbox"></td><td><a class="delete">删除</a></td></tr>';
							d.append(tr);
						});

						$.each(d.find("tr input[type='checkbox'], tr select"), function() {
							var $this = $(this);
							if ($this.attr("type") == "checkbox") {
								if ($this.attr("value") == "true") {
									$this.prop("checked", "checked");
								}
							} else {
								$this.val($(this).attr("value"));
							}
						});
					}
					for (var j = 0; j < data.datas[0].bulkstocks.length; j++) {
						commodities.bulkstockCategoryId.push(data.datas[0].bulkstocks[j].bulkstockCategoryId);
						commodities.publicity.push(data.datas[0].bulkstocks[j].publicity);
						commodities.volumes.push(data.datas[0].bulkstocks[j].volume);
						commodities.weights.push(data.datas[0].bulkstocks[j].weight);
						commodities.units.push(data.datas[0].bulkstocks[j].unit);
						commodities.quantitys.push(data.datas[0].bulkstocks[j].quantity);
						commodities.originPlaces.push(data.datas[0].bulkstocks[j].originPlace);
						commodities.commodityNumbers.push(data.datas[0].bulkstocks[j].bulkstockNumber);
						commodities.specifications.push(data.datas[0].bulkstocks[j].specification);
						commodities.manufacturers.push(data.datas[0].bulkstocks[j].manufacturer);
						commodities.commodityNames.push(data.datas[0].bulkstocks[j].bulkstockName);
						commodities.bulkstockIds.push(data.datas[0].bulkstocks[j].bulkstockInfoId);
						commodities.bulkstockIds1.push(data.datas[0].bulkstocks[j].bulkstockId);
						commodities.bulkstockValuations.push(data.datas[0].bulkstocks[j].bulkstockValuation);
						commodities.bulkstockPrices.push(data.datas[0].bulkstocks[j].bulkstockPrice);
						commodities.cargoMark.push(data.datas[0].bulkstocks[j].cargoMark);
						commodities.coldStorage.push(data.datas[0].bulkstocks[j].coldStorage);
						commodities.dangerous.push(data.datas[0].bulkstocks[j].dangerous);
						commodities.declaration.push(data.datas[0].bulkstocks[j].declaration);
						commodities.instructionManual.push(data.datas[0].bulkstocks[j].instructionManual);
						commodities.dangerousRemark.push(data.datas[0].bulkstocks[j].dangerousRemark);
						commodities.unNum.push(data.datas[0].bulkstocks[j].unNum);
						commodities.imdg.push(data.datas[0].bulkstocks[j].imdg);
						commodities.coolLetter.push(data.datas[0].bulkstocks[j].coolLetter);
						commodities.coolRemark.push(data.datas[0].bulkstocks[j].coolRemark);
						commodities.vent.push(data.datas[0].bulkstocks[j].vent);
						commodities.tempMin.push(data.datas[0].bulkstocks[j].tempMin);
						commodities.tempMax.push(data.datas[0].bulkstocks[j].tempMax);
						commodities.tempUnit.push(data.datas[0].bulkstocks[j].tempUnit);
						commodities.setTemperature.push(data.datas[0].bulkstocks[j].setTemperature);
						commodities.tempUpDown.push(data.datas[0].bulkstocks[j].tempUpDown);
						commodities.plugType.push(data.datas[0].bulkstocks[j].plugType);
						commodities.plug.push(data.datas[0].bulkstocks[j].plug);
						commodities.ptiOk.push(data.datas[0].bulkstocks[j].ptiOk);
						commodities.precool.push(data.datas[0].bulkstocks[j].precool);
					}
					$("#commodityCategory").val(data.datas[0].bulkstockCategoryId);
					$("#deliverProvince").val(data.datas[0].deliverProvinceId);
					$("#deliverCity").html('<option value="' + data.datas[0].deliverCityId + '">' + data.datas[0].deliverCity + '</option>');
					$("#deliverDistrict").html('<option value="' + data.datas[0].deliverDistrictId + '">' + data.datas[0].deliverDistrict + '</option>');
					$("#receiveProvince").val(data.datas[0].receiveProvinceId);
					$("#receiveCity").html('<option value="' + data.datas[0].receiveCityId + '">' + data.datas[0].receiveCity + '</option>');
					$("#receiveDistrict").html('<option value="' + data.datas[0].receiveDistrictId + '">' + data.datas[0].receiveDistrict + '</option>');
					$("#loanMethod").val(data.datas[0].loanMethod);
					$("#loanTimeLimit").val(data.datas[0].loanTimeLimit);
					$("#estimateInterest").html(data.datas[0].estimateInterest);
					fillgoods(commodities, data.datas[0].bulkstocks.length);
					setTimeout(function() {
						$.each($(".commodityNames"), function(index, item) {
							$(this).val(data.datas[0].bulkstocks[index].bulkstockInfoId);
							$(this).parents(".goods").find(".commodityNames").find("option:selected").text();
							$(this).parents(".goods").find(".bulkstockNames").val($(this).parents(".goods").find(".commodityNames").find("option:selected").text());
						});
						
						if (productType == 4) {
						
							$("input[name=enterpriseInsuranceNumber]").parents(".dataLine").remove();
							$("input[name=enterpriseForceAmount]").parents(".dataLine").remove();
							$("input[name=enterpriseInsuranceAmount]").parents(".dataLine").remove();
							$("input[name=declaredValue]").parents(".applyDataLine").remove();
							$(".goodsfrom .star").remove();
							$("#receiveProvince").attr("isNull", "0");
							$(".receiveProvince").attr("isNull", "0");
							$("#receiveCity").attr("isNull", "0");
							$(".receiveCity").attr("isNull", "0");
							$(".goodsto .star").remove();
							$("#deliverProvince").attr("isNull", "0");
							$(".deliverProvince").attr("isNull", "0");
							$("#deliverCity").attr("isNull", "0");
							$(".deliverCity").attr("isNull", "0");
							$("#deliverAddress").attr("isNull", "0");
							$("#receiveAddress").attr("isNull", "0");
							$("input[name=bookingSpaceNumber]").parents(".applyDataLine").remove();
	//						$("input[name=enterpriseInsuranceNumber]").parents(".applyDataLine").remove();
							$("#addCaseInfo").remove();
							
							$("input[name=weights]").val(1);
							$("input[name=volumes]").val(1).parent().addClass("none");
							$(".valuationLink").attr("style", "visibility: hidden; margin-right: 100px;");
							$(".receiver").html("出质");
							$(".deliver").html("债务");
							
							$(".require_package").remove();
							$(".require_tag").remove();
							$(".require_storage").remove();
							$(".require_keep").remove();
							$(".label_info3").remove();
							$(".line:last").remove();
							
							$(".cargoMark").parent().remove();
							$("#coldStorage").parent().parent().remove();
							inquireBulkstockPageList($("#commodityCategory").val(), $(".commodityNames"));
							
							tools.loadList("inquireLogisticsCompanyAll.json", $("#deliverList"), $("#deliverList script"), null, function(){
							}, null);
							
							$("#commodityCategoryHidden").parent().parent().find(".bulkstockCategory").html("产品类别");
							$("#commodityCategoryHidden").attr("codeName", "产品类别");
							$("#commodityCategory").attr("codeName", "产品类别");
							
							$("select[name=bulkstockInfoIds]").attr("codeName", "产品名称");
							$("#goods1 .label").remove();
							$(".goods_name .bulkstockName").html("产品名称");
							$(".manufacturers").parent().remove();
							$(".bulkstockValuationName").html("发票总价");
							$(".goodsto .select_label").html("出质方地址：");
							$(".goodsto").css("margin-left", "0");
							$(".goodsfrom .select_label").html("债务方地址：");
							$(".goodsfrom").css("margin-left", "0");
							$(".labeltitle").html("票据信息");
							$("#progress").attr("src", "../../../res/png/progress_apply11.png");
						} else {
							$(".freightListInfo").remove();
						}
					}, 1000);
					
				} else {
					//                  base.alert(2,"信息获取失败");
				}
				
				
			}
		});
	};

	//获取货物类别
	var getCommodityCategory = function() {
		base.fnAjax({
			action: "inquireBulkstockCategoryPageList.json",
			async: false,
			nocode: true,
			oData: {
				activeState: true,
				productType: productType
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#commodityCategoryTpl").html();
					var html = juicer(tpl, data);
					$("#commodityCategory").html(html);
					
					if (productType == 4) {
						
						$("input[name=enterpriseInsuranceNumber]").parents(".dataLine").remove();
						$("input[name=enterpriseForceAmount]").parents(".dataLine").remove();
						$("input[name=enterpriseInsuranceAmount]").parents(".dataLine").remove();
						$("input[name=declaredValue]").parents(".applyDataLine").remove();
						$(".goodsfrom .star").remove();
						$("#receiveProvince").attr("isNull", "0");
						$(".receiveProvince").attr("isNull", "0");
						$("#receiveCity").attr("isNull", "0");
						$(".receiveCity").attr("isNull", "0");
						$(".goodsto .star").remove();
						$("#deliverProvince").attr("isNull", "0");
						$(".deliverProvince").attr("isNull", "0");
						$("#deliverCity").attr("isNull", "0");
						$(".deliverCity").attr("isNull", "0");
						$("#deliverAddress").attr("isNull", "0");
						$("#receiveAddress").attr("isNull", "0");
						$("input[name=bookingSpaceNumber]").parents(".applyDataLine").remove();
//						$("input[name=enterpriseInsuranceNumber]").parents(".applyDataLine").remove();
						$("#addCaseInfo").remove();
						
						$("input[name=weights]").val(1);
						$("input[name=volumes]").val(1).parent().addClass("none");
						$(".valuationLink").attr("style", "visibility: hidden; margin-right: 100px;");
						$(".receiver").html("出质");
						$(".deliver").html("债务");
						
						$(".require_package").remove();
						$(".require_tag").remove();
						$(".require_storage").remove();
						$(".require_keep").remove();
						$(".label_info3").remove();
						$(".line:last").remove();
						
						$(".cargoMark").parent().remove();
						$("#coldStorage").parent().parent().remove();
//						$("#commodityCategory").attr("disabled", "disabled");
//						$("#commodityCategory option[txt='保理业务']").attr("selected", true);
//						$("#commodityCategoryHidden").val("保理业务");
						inquireBulkstockPageList($("#commodityCategory").val(), $(".commodityNames"));
						
						tools.loadList("inquireLogisticsCompanyAll.json", $("#deliverList"), $("#deliverList script"), null, function(){
						}, null);
						
						$("#commodityCategoryHidden").parent().parent().find(".bulkstockCategory").html("产品类别");
						$("#goods1 .label").remove();
						$(".goods_name .bulkstockName").html("产品名称");
						$(".manufacturers").parent().remove();
						$(".bulkstockValuationName").html("发票总价");
						$(".goodsto .select_label").html("出质方地址：");
						$(".goodsto").css("margin-left", "0");
						$(".goodsfrom .select_label").html("债务方地址：");
						$(".goodsfrom").css("margin-left", "0");
						
						$(".labeltitle").html("票据信息");
						$("#progress").attr("src", "../../../res/png/progress_apply11.png");
					} else {
						$(".freightListInfo").remove();
					}
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};

	//获取货物类别详情
	var inquireBulkstockCategoryDetail = function(bulkstockCategoryId) {
		base.fnAjax({
			action: "inquireBulkstockCategoryDetail.json",
			async: true,
			nocode: true,
			oData: {
				bulkstockCategoryId: bulkstockCategoryId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var str = "";
					for (var j = 0; j < data.datas[0].templates.length; j++) {
						str += data.datas[0].templates[j].templateName + ",";
					}
					str = str.substring(0, str.length - 1);
					$("#bulkstockMaterial").html(str);
					$(".bulkstockMaterial").removeClass("none");
					$(".bulkstockMaterial").css("display", "block");

				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};

	//大宗商品列表
	var inquireBulkstockPageList = function(bulkstockCategoryId, dom) {
		base.fnAjax({
			action: "inquireBulkstockPageList.json",
			async: false,
			nocode: true,
			oData: {
				bulkstockCategoryId: bulkstockCategoryId,
				pageSize: 100
			}, //传递参数
			fnSuccess: function(data) {
				bulkstockObj = {
					bulkstockId: [],
					bulkstockName: [],
					specificationName: [],
					bulkstockNumber: [],
					measurement: [],
					conversionFactor: []
				};
				if (data.status == 200) {
					for (var j = 0; j < data.datas.length; j++) {
						bulkstockObj.bulkstockName.push(data.datas[j].bulkstockName);
						bulkstockObj.bulkstockId.push(data.datas[j].bulkstockInfoId);
						bulkstockObj.bulkstockNumber.push(data.datas[j].bulkstockNumber);
						bulkstockObj.specificationName.push(data.datas[j].specificationName);
						bulkstockObj.measurement.push(data.datas[j].measurement);
						bulkstockObj.conversionFactor.push(data.datas[j].conversionFactor);
					}
					$(dom).children().remove();
					$(dom).append('<option value="">请选择货物名称</option>');
					for (var j = 0; j < bulkstockObj.bulkstockName.length; j++) {
						var str = '<option value="' + bulkstockObj.bulkstockId[j] + '" measurement="' + bulkstockObj.measurement[j] + '"  conversionFactor="' + bulkstockObj.conversionFactor[j] + '">' + bulkstockObj.bulkstockName[j] + '(' + bulkstockObj.specificationName[j] + ')' + '</option>';
						$(dom).append(str);
					}
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};

	//填充货物货物
	var fillgoods = function(commodities, numbers) {
		var newNode = nd;
		$("#goods1").remove();
		i -= 1;
		for (var j = 0; j < numbers; j++, i++) {
			var nNode = newNode.clone();
			inquireBulkstockPageList(commodities.bulkstockCategoryId, nNode.find(".commodityNames"));
			nNode.attr("bulkstockIds1", commodities.bulkstockIds1[j]);
			nNode.find(".bulkstockIds").val(commodities.bulkstockIds1[j]);
			nNode.attr("id", "goods" + i);
			nNode.find(".labelName").html("货物" + i);
			nNode.find(".originPlaces").val(commodities.originPlaces[j]);
			nNode.find(".quantitys").val(commodities.quantitys[j]);
			nNode.find(".units").val(commodities.units[j]);
			nNode.find(".weights").val(commodities.weights[j]);
			nNode.find(".bulkstockPrice").val(commodities.bulkstockPrices[j]);
			nNode.find(".bulkstockValuation").val(commodities.bulkstockValuations[j]);
			nNode.find(".cargoMark").val(commodities.cargoMark[j]);
			nNode.find(".unNum").val(commodities.unNum[j]);
			nNode.find(".dangerousRemark").val(commodities.dangerousRemark[j]);
			nNode.find(".imdg").val(commodities.imdg[j]);
			nNode.find(".coolRemark").val(commodities.coolRemark[j]);
			nNode.find(".vent").val(commodities.vent[j]);
			nNode.find(".tempMin").val(commodities.tempMin[j]);
			nNode.find(".tempMax").val(commodities.tempMax[j]);
			nNode.find(".tempUnit").val(commodities.tempUnit[j]);
			nNode.find(".setTemperature").val(commodities.setTemperature[j]);
			nNode.find(".tempUpDown").val(commodities.tempUpDown[j]);
			nNode.find(".plugType").val(commodities.plugType[j]);
			nNode.find(".plug").val(commodities.plug[j]);
			nNode.find(".ptiOk").val(commodities.ptiOk[j]);
			nNode.find(".precool").val(commodities.precool[j]);
			nNode.find(".coldStorage").val(commodities.coldStorage[j]);
			nNode.find(".dangerous").val(commodities.dangerous[j]);
			nNode.find(".volumes").val(commodities.volumes[j]);
			nNode.find(".manufacturers").val(commodities.manufacturers[j]);
			nNode.find(".quantitys").val(commodities.quantitys[j]);
			if (commodities.coldStorage[j] == true) {
				nNode.find(".coolLetter").html(tools.inquireFile(commodities.coolLetter[j])).css({
					"background-image": "none",
					"padding-left": "0"
				});
				nNode.find(".coolLetter").parent().find(".valueInput").val(commodities.coolLetter[j]);
				nNode.find(".coldStorage").removeClass("none");
				nNode.find("#coldStorage").prop("checked", "checked");
				if (nNode.find(".precool").attr("value") == "true") {
					nNode.find(".precool").parent().find(".valueInput").val(1);
					nNode.find(".precool").prop("checked", "checked");
				}

				if (nNode.find(".ptiOk").attr("value") == "true") {
					nNode.find(".ptiOk").parent().find(".valueInput").val(1);
					nNode.find(".ptiOk").prop("checked", "checked");
				}

				if (nNode.find(".plug").attr("value") == "true") {
					nNode.find(".plug").parent().find(".valueInput").val(1);
					nNode.find(".plug").prop("checked", "checked");
				}
			} else {
				nNode.find(".coldStorage").addClass("none");
			}

			if (commodities.dangerous[j] == true) {
				nNode.find(".instructionManual").html(tools.inquireFile(commodities.instructionManual[j])).css({
					"background-image": "none",
					"padding-left": "0"
				});
				nNode.find(".instructionManual").parent().find(".valueInput").val(commodities.instructionManual[j]);
				nNode.find(".declaration").html(tools.inquireFile(commodities.declaration[j])).css({
					"background-image": "none",
					"padding-left": "0"
				});
				nNode.find(".declaration").parent().find(".valueInput").val(commodities.declaration[j]);
				nNode.find(".dangerous").removeClass("none");
				nNode.find("#dangerous").prop("checked", "checked");
			} else {
				nNode.find(".dangerous").addClass("none");
			}

			if (commodities.publicity[j] == 1) {
				nNode.find(".publicity").val("true");
			} else {
				nNode.find(".publicity").val("false");
			}

			$(".continute_add").before(nNode);
			i = $(".goods").length;
			if (i == 2) {
				$(".continute_delete").addClass("none");
			} else {
				$(".continute_delete").removeClass("none");
			}
		}
	};

	//货物估值变动事件
	var changeBulkstockValuationEven = function() {
		//货物估值变动
		$(".bulkstockValuation").unbind("change").change(function() {
			changeBulkstockValuation();
		});

		//只支持IE输入框变化
		$('.bulkstockValuation').bind('input propertychange', function() {
			changeBulkstockValuation();
		});
		//只支持输入框变化
		$('.bulkstockValuation').bind('input oninput', function() {
			changeBulkstockValuation();
		});
	}

	//货物估值变动
	var changeBulkstockValuation = function() {
			var valuation = 0;
			$(".bulkstockValuation").each(function(i, val) {
				valuation += parseFloat($(this).val());
			});
			$("#valuation").val(valuation.toFixed(2));
			$("#chineseMoney").html(tools.changeMoneyToChinese(valuation.toFixed(2)));
		}
		//	删除最后一条货物
	var deletegoods = function() {
		if (i > 2) {
			$("#goods" + (i - 1)).remove();
			i--;
		}
		if (i <= 2) {
			$(".continute_delete").addClass("none");
		}
	}

	//上传文件
	var uploadFile = function(fileElementId) {
		$.ajaxFileUpload({
			url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
			secureuri: false,
			fileElementId: fileElementId,
			dataType: 'json',
			async: true,
			success: function(data) {
				var dom = $(document.getElementById(fileElementId));
				dom.parent().find(".valueInput").val(data.data[0].fileUuid);
				dom.parent().find("label").html(data.data[0].fileName).css({
					"background": "none",
					"padding": "0"
				});
			},
			complete: function(xml) {},
			error: function(data, status, e) {
				base.alert(2, "参数错误");
			}
		});
	};
	
	var existBulkstockPledgeRate = function(bulkstockInfoId, pledgeRate, loanRate) {
		base.fnAjax({
			action: "existBulkstockPledgeRate.json",
			async: false,
			nocode: true,
			oData: {
				bulkstockInfoId: bulkstockInfoId,
				productType: productType,
				pledgeRate: pledgeRate,
				loanRate: loanRate
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (!data.datas[0].isExist) {
						layer.msg("对不起，您暂无该货物的融资权限，请联系客服!");
					}
				} else {
					layer.msg(data.message);
				}
			}
		});
	};
	
	var existBulkstockPledgeRate = function(bulkstockInfoId, pledgeRate, loanRate) {
		base.fnAjax({
			action: "existBulkstockPledgeRate.json",
			async: false,
			nocode: true,
			oData: {
				bulkstockInfoId: bulkstockInfoId,
				productType: productType,
				pledgeRate: pledgeRate,
				loanRate: loanRate
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if (!data.datas[0].isExist) {
						layer.msg("对不起，您暂无该货物的融资权限，请联系客服!");
					}
				} else {
					layer.msg(data.message);
				}
			}
		});
	};
	
	var loginByUserId = function(userId) {
		base.fnAjax({
			action: "loginByUserId.json",
			async: false,
			nocode: true,
			oData: {
				appKey: "FINANCE-ENTERPRISE-WEB",
				userId: userId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.saveData("sid", data.datas[0].sessionUuid); //存sessionUuid
					base.saveData("appKey", "FINANCE-ENTERPRISE-WEB"); //存appkey
					$("input[name=bookingSpaceNumber]").val(PONO);
//					alert(data.datas[0].sessionUuid);
					getPODetail();
				} else {
					layer.msg(data.message);
					location.href = "../login/login.html";
				}
			}
		});
	};

	return {
		init: init
	};
});